﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlogTruyen.Models;
using System.Collections.ObjectModel;
using HtmlAgilityPack;
using System.Windows;
using System.Net;

namespace BlogTruyen.ViewModels
{
    public class Home:BaseModel
    {
        public ObservableCollection<Story> items { get; set; }
        public bool isLoaded { get; private set; }
        public string nextPage { get; private set; }
        public Home()
        {
            items = new ObservableCollection<Story>();
        }

        public void LoadHtml(string html)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            var sections = doc.DocumentNode.SelectNodes("//section[@class='bg-white storyitem']");
            HtmlNode fll, a, img, flr, pSumm,spanCount,spanDate;
            foreach (HtmlNode section in sections)
            {
                fll  = section.SelectSingleNode("./div[@class='fl-l']");
                a = fll.SelectSingleNode("./a");
                img = a.SelectSingleNode("./img");
                flr = section.SelectSingleNode("./div[@class='fl-r']");
                pSumm = flr.SelectSingleNode("./p");
                spanCount = section.SelectSingleNode(".//span[@class='count']").SelectSingleNode("span");
                spanDate = section.SelectSingleNode(".//span[@class='publishedDate']");
                items.Add(new Story
                {
                    update_date = spanDate.InnerText,
                    chapter_count = spanCount.InnerText,
                    summary = HttpUtility.HtmlDecode(pSumm.InnerText).Trim(),
                    title = HttpUtility.HtmlDecode(a.GetAttributeValue("title", "")),
                    cover_img = img.GetAttributeValue("src", ""),
                    url = img.ParentNode.GetAttributeValue("href","")
                });
            }

            //next page
            nextPage = null;
            var pagingHome = doc.DocumentNode.SelectSingleNode("//div[@id='pagingHome']");
            if (pagingHome != null)
            {
                var currentPage = pagingHome.SelectSingleNode("./span[@class='current_page']");
                var pageNodes = pagingHome.SelectNodes("./span");
                var currentPageIndex = pageNodes.IndexOf(currentPage);

                if (currentPageIndex < pageNodes.Count - 1)
                {
                    nextPage = pageNodes[currentPageIndex + 1].SelectSingleNode("./a").GetAttributeValue("href", "");
                }
            }
            isLoaded = true;
        }
    }
}
